package com.yc.myspringboot.webSocket.demo1;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * description: webSocket 服务端事件处理
 * author: yc
 * date: 2021/4/29 14:05
 */
@ServerEndpoint("/webSocketServer")
@Component
public class WebSocketDemo {

    private Session session;//当前连接会话
    private String name;//当前客户端用户名
    private static ConcurrentHashMap<String, WebSocketDemo> webSocketSet = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        this.name = session.getId();
        this.webSocketSet.put(name, this);
        System.out.println("新开启一个webSocket链接" + session.getId() + ", 目前连接人数：" + webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("收到客户端发送的信息: " + message);
        System.out.println("当前的sessionId: " + session.getId());
        //判断是否需要指定发送，具体规则自定义
        if(message.indexOf("TOUSER") == 0){
            String name = message.substring(message.indexOf("TOUSER")+6,message.indexOf(";"));
            AppointSending(name,this.name + " : " + message.substring(message.indexOf(";")+1,message.length()));
        }else{
            GroupSending(this.name + " : " + message);
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        System.out.println("webScoket连接关闭：sessionId:" + session.getId() +
                "，关闭原因："+reason.getReasonPhrase() + ", code: " + reason.getCloseCode());
        this.webSocketSet.remove(session.getId());
    }

    @OnError
    public void onError(Throwable t) {
        t.printStackTrace();
    }

    /**
     * 群发
     * @param message
     */
    public void GroupSending(String message){
        for (String name : webSocketSet.keySet()){
            try {
                webSocketSet.get(name).session.getBasicRemote().sendText(message);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 定向发送
     * @param name
     * @param message
     */
    public void AppointSending(String name,String message){
        try {
            webSocketSet.get(name).session.getBasicRemote().sendText(message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
